﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;

namespace JNPF.Utils.Controller
{
    /// <summary>
    /// 登录认证
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class FilterLogin : Attribute, IAuthorizationFilter
    {
        /// <summary>
        /// 执行验证
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var userProvider = new UserProvider();
            //允许匿名访问
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
                return;
            //Token验证
            if (string.IsNullOrEmpty(RequestAuthorize.GetRequestToken))
            {
                context.Result = new ObjectResult(new ResponseResult() { code = ResponseCode.SessionError, msg = "Token验证失败" });
                return;
            }
            //是否过期
            if (!userProvider.IsOverdue)
            {
                context.Result = new ObjectResult(new ResponseResult() { code = ResponseCode.SessionOverdue, msg = "登录过期,请重新登录" });
                return;
            }
            //是否在线
            if (userProvider.IsOnLine)
            {
                //CacheFactory.Cache.Remove(userProvider.Get().Id);
                context.Result = new ObjectResult(new ResponseResult() { code = ResponseCode.SessionOffLine, msg = "您的帐号在其他地方已登录,被强制踢出" });
                return;
            }
        }


    }
}